<template>
  <div>
    <!--    <hte-file-class-form ref="realForm" @ok="submitCallback" :disabled="disableSubmit"></hte-file-class-form>-->
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button icon="plus" @click="handleAdd">添加共享</a-button>
      <a-button icon="delete" @click="handleDel">删除</a-button>
    </div>
    <!-- table区域-begin -->
    <div>
       <a-tooltip :overlayStyle="{ width: '412px' }" overlayClassName="new-tooltip">
                  <template slot="title">
                   共享范围原则：<br />  
                    1、文件大类共享范围和当前设置范围的并集。<br />
                  </template>
      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: true }"
        bordered
        row-key="id"
        :columns="columns"
        :data-source="tableData"
        :pagination="ipagination"
        :loading="loading"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      />
       </a-tooltip>
    </div>

    <!-- <a-modal
      title="添加共享范围"
      :width="700"
      :visible="addVisible"
      :confirm-loading="confirmLoading"
      @ok="handleAddOk"
      @cancel="handleAddCancel"
      :maskClosable="false"
    >
      <a-form-model ref="form" :model="model" :rules="validatorRules" style="width: 600px">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="对象类型：" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-radio-group
                v-model="model.objectType"
                name="radioGroup"
                :default-value="1"
                @change="handleObjectChange"
              >
                <a-radio :value="1"> 私有组 </a-radio>
                <a-radio :value="2"> 发送人员 </a-radio>
                <a-radio :value="3"> 组织架构 </a-radio>
              </a-radio-group>
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item label="对象名称" :label-col="labelCol" :wrapper-col="wrapperCol" prop="selectObject">
              <a-select
                v-if="model.objectType < 3"
                ref="selectRef"
                v-model="model.selectObject"
                mode="multiple"
                placeholder="请输入对象名称"
                style="width: 100%"
                :filter-option="false"
                :not-found-content="fetching ? '找不到记录' : null"
                :labelInValue="true"
                @search="fetchObj"
                @change="selectObjectChange"
              >
                <a-spin v-if="fetching" slot="notFoundContent" size="small" />
                <a-select-option v-for="d in objData" :key="d.value" :value="d.value">
                  {{ d.label }}
                </a-select-option>
              </a-select>
              <a-tree-select
                      v-if="model.objectType === 3"
                      v-model="model.selectObject"
                      :tree-data="treeData"
                      tree-checkable
                      showCheckedStrategy="SHOW_CHILD"
                      :replaceFields="{ children: 'children', title: 'title', key: 'id', value: 'id' }"
                      :maxTagCount="3"
                      search-placeholder="请选择组织架构"
                      :labelInValue="true"
              >
              </a-tree-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="权限" :label-col="labelCol" :wrapper-col="wrapperCol" prop="authority">
              <a-select v-model="model.authority" mode="multiple" placeholder="请选择权限">
                <a-select-option
                  v-for="option in authorityOptions"
                  :key="'auth' + option.value"
                  :value="option.value"
                  :defaultValue="[1]"
                  :disabled="option.disabled"
                  >{{ option.label }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal> -->
    <file-range-add :saveData='tableData' :fileType="classId" :visible="addVisible" ref="fileRangeAdd" @handleAddCancel='handleAddCancel' @handleAddOk="handleAddOk"></file-range-add>
  </div>
</template>

<script>
import { postAction, getAction } from '@/api/manage';
import FileRangeAdd from '@/views/library/modules/FileRangeAdd'
export default {
  name: 'BatchFileRange',
  components: {FileRangeAdd},
  props: {
    hteFile: {
      type: Object,
      default: () => {}
    },
    classId:{
      type: Number,
      default:null
    }
  },
  data() {
    return {
      authorityOptions: [
        { value: '1', label: '查阅', disabled: false },
        { value: '2', label: '编辑', disabled: false },
        { value: '3', label: '下载', disabled: false },
        { value: '4', label: '可废除', disabled: false },
        { value: '5', label: '一级发布', disabled: true }
      ],
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '对象类型 ',
          align: 'center',
          dataIndex: 'objectType',
          customRender: text => {
            if (text == 1) {
              return '私有组';
            } else if (text == 2) {
              return '发送人员';
            }else if (text == 3) {
              return '组织架构';
            }
            else if (text == 4) {
              return '所有人公开';
            }
            return text;
          }
        },

        {
          title: '对象名称',
          align: 'center',
          dataIndex: 'objectName'
        },
        {
          title: '共享类型 ',
          align: 'center',
          dataIndex: 'shareType',
          customRender: (text) => {
            if (text == 1) {
              return '默认共享'
            } else if (text == 2) {
              return '文件共享'
            } else if (text == 3) {
              return '分发共享'
            }
            return text
          },
        },
        {
          title: '权限',
          align: 'center',
          dataIndex: 'authority',
          customRender: text => {
            var str = '';
            if (text && text.indexOf('1') >= 0) {
              str += '查阅,';
            }
            if (text && text.indexOf('2') >= 0) {
              str += '编辑,';
            }
            if (text && text.indexOf('3') >= 0) {
              str += '下载,';
            }
            if (text && text.indexOf('4') >= 0) {
              str += '可废除,';
            }
            if (text && text.indexOf('5') >= 0) {
              str += '一级发布,';
            }
            if (str.length > 1) {
              return str.substr(0, str.length - 1);
            }
            return str;
          }
        },
        {
          title: '创建人',
          align: 'center',
          dataIndex: 'createUserName'
        },
        {
          title: '创建时间',
          align: 'center',
          dataIndex: 'createTime'
        }
      ],
      tableData: [],
      dataSource: [],
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条';
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
        name: ''
      },
      loading: false,
      title: '',
      width: 800,

      disableSubmit: false,
      data: [],
      selectedRowKeys: [],
      rowKeyIndex: -1,
      addVisible: false,
      confirmLoading: false,
      model: { objectType: 1, client: '海芯', objectId: [], selectObject: [] },
      validatorRules: {
        authority: [{ required: true, message: '请选择权限' }],
        objectId: [{ required: true, message: '请输入选择' }]
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      objData: [],
      fetching: false,
      treeData: [],
      url: {
        list: '/lib/hteFileClassRange/list',
        getUserList: '/lib/hteFileClass/getUserList',
        getGroupList: '/lib/hteLibraryGroup/groupList',
        getClassAuthority: '/lib/hteFileClass/getClassAuthority',
        getDeptTree: '/lib/hteDict/getDeptTree',
      }
    };
  },

  created() {
    const that = this
    getAction(this.url.getDeptTree, {}).then(res => {
      if (res.success) {
        that.treeData = res.result;
      } else {
        that.$message.error('获取组织架构数据错误');
      }
    });
  },
  methods: {
    handleAdd() {
      if(!this.classId){
        this.$message.error('请先添加文件属性');
        return
      }
      this.addVisible = true;
      this.model = { objectType: 1, client: '海芯', objectId: [] };
    },
    handleAddOk(data) {
      const that = this;
      data.shareType=2
      
      that.tableData.push(data);
      this.handleAddCancel();
      
      console.log(JSON.stringify(data));
    },
    loadRange(classId) {
      this.tableData = []
      let param = Object.assign({}, this.ipagination)
      delete param.pageSizeOptions
      delete param.showTotal
      getAction(this.url.list + '/' + classId, param).then((res) => {
        if (res.success) {
          if (res.result.total) {
            this.ipagination.total = res.result.total
          } else {
            this.ipagination.total = 0
          }
          this.tableData = res.result.records
          this.tableData.forEach(it=>{
            it.shareType=1
          })
        }
      })
    },
    handleAddCancel() {
      this.addVisible = false;
    },

    handleDel() {
      var that = this;
      var pass = 1;
      debugger;
      this.selectedRowKeys.forEach(it => {
        const rowData = that.tableData.find(v => v.id === it);
        if (rowData.shareType === 1) {
          pass = 0;
        }
      });
      if (pass == 0) {
        that.$message.error('默认共享不能删除');
        return false;
      }
      this.$confirm({
        title: '确认删除',
        content: '是否删除选中数据?',
        onOk: function() {
          let ids = '';
          that.selectedRowKeys.forEach(key => {
            if (key > 0) {
              ids += key + ',';
            }
            const index = that.tableData.findIndex(v => v.id === key);
            if(index != -1){
              that.tableData.splice(index, 1);  
            }
            
          });
          that.selectedRowKeys = []
        }
      });
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    fetchObj(val) {
      this.objData = [];
      this.fetching = true;
      let url = this.url.getGroupList;
      if (this.model.objectType === 2) {
        url = this.url.getUserList;
      }
      getAction(url, { name: val }).then(res => {
        if (res.success) {
          this.objData = res.result;
          if (res.result.length > 0) {
            this.fetching = false;
            if (this.model.objectType == 2) {
              res.result.forEach(it => {
                this.objData.push({ label: it.realname, value: it.username });
              });
            } else {
              res.result.forEach(it => {
                this.objData.push({ label: it.name, value: it.id });
              });
            }
          }
        }
      });
    },
    handleTableChange(pagination, filters, sorter) {
      // 分页、排序、筛选变化时触发
      if (Object.keys(sorter).length > 0) {
        this.$set(this.isorter, 'column', sorter.field);
        this.$set(this.isorter, 'order', sorter.order === 'ascend' ? 'asc' : 'desc');
      }
      this.ipagination = pagination;
      this.$set(this.ipagination, 'pageNo', this.ipagination.current);
      this.loadRange(this.hteFile);
    },
    handleObjectChange() {
      this.$set(this.model, 'objectId', []);
      this.$set(this.model, 'authority', []);
      this.objData = [];
      const forwardOption = this.authorityOptions.find(value => value.value === '5');
      if (forwardOption && this.model.objectType === 1) {
        this.$set(forwardOption, 'disabled', true);
      } else if (forwardOption) {
        this.$set(forwardOption, 'disabled', false);
      }
    },
    selectObjectChange() {
      this.$refs.selectRef.blur();
    }
  },

};
</script>
